<template>
	<div class="left-box">
		<div class="heade-wrapper">
			<a-input-group compact >
				<a-select
					v-model="selectValue"
					@change="onChangeCondition"
					class="heade-left-box"
				>
					<a-select-option
						v-for="(item, index) in selectOptions"
						:value="item.id"
						:key="index"
					>
						{{ item.name }}
					</a-select-option>
				</a-select>
				<div class="heade-right-box" v-if="selectType !== 'unitName'">
					<a-select
						class="select-list"
						v-model="selectSecondValue"
						@change="onSelectSecondChange"
					>
						<a-select-option
							v-for="(item, index) in selectSecondOptions"
							:value="item.id"
							:key="index"
						>
							{{ item.name }}
						</a-select-option>
					</a-select>
					<a-button @click="onDoSearch" class="select-list-btn" >
						<a-icon type="search" />
					</a-button>
				</div>
				<div class="heade-right-box" v-else>
					<a-input-search
						:placeholder="this.$i18n('selectPeople.input',this.$i18n('org.account.label'))"
						v-model.trim="searchValue"
						@search="onSearchHandle"
					/>
				</div>
			</a-input-group>
		</div>
		<top-bottom-layout
			ref="leftLayout"
			class="content-wrapper"
			:isShowDown="isShowDown"
			@toShowDown="onShowDown"
		>
			<template #top>
				<transfer-tree
					:checkable="true"
					:checkStrictly="true"
					:checkedList="accountCheckedList"
					:defaultExpandedKeys="defaultExpandedKeys"
					:treeData="treeData"
					@toCheckedNode="onAccountCheckedNode"
				></transfer-tree>
			</template>
			<template #middle></template>
			<template #bottom>
				<scrollList
					ref="scrollList"
					panel="Account"
					command="orgAccountTree"
					:showOtherProp="false"
					:firstLoadSearch="firstLoadSearch"
					:checkAllShow="false"
				></scrollList>
			</template>
		</top-bottom-layout>
	</div>
</template>

<script>
import transferTree from '@/components/transferTree';
import topBottomLayout from '@/components/topBottomLayout';
import scrollList from '@/components/scrollList';
import {mapActions, mapState} from 'vuex';
import {getPanelData} from '@/api/modules/SelectOrgApi';
import {EntityTypes, GroupId} from '@/utils/orgConstants';
import {getSelectKey} from '@/utils/utils';
import {
	ACTION_ADD_ENTITY,
	ACTION_REMOVE_ENTITY,
	ACTION_TOGGLE_ENTITY
} from '@/store/actionTypes';
import {BtnType, Dialog} from '@/components/dialog';
import {CheckUtils} from '@/utils/checkUtils';
import {MaskAsync} from '@/utils/Mask.js';

export default {
	name: 'Account',
	components: {
		transferTree,
		topBottomLayout,
		scrollList
	},
	inject: ['app'],
	data() {
		return {
			selectValue: '',
			searchValue: '',
			searchData: {},
			selectSecondOptions: [],
			selectSecondValue: [],
			accountCheckedList: [],
			defaultExpandedKeys: [],
			firstLoadSearch: false,
			isShowDown: true,
			treeData: [],
			accountIds: []

		};
	},
	computed: {
		...mapState('selectData', ['selectedUUIDMap']),
		orgPanel() {
			return this.app().tabs;
		},
		orgSelect() {
			return this.app().orgSelect;
		},
		selectOptions() {
			let metadataList = [];
			for (let item of this.app().tabs) {
				if (item.name === 'Account') {
					metadataList = item.extInfo.metadataList;
				}
			}
			return metadataList;
		},
		selectType() {
			let type = 'unitName';
			let index = this.selectOptions.findIndex(
				(el) => el.id === this.selectValue
			);
			if (index !== -1) {
				type = this.selectOptions[index].searchType;
			}
			return type;
		},
		maxSize() {
			return this.orgSelect.maxSize.toString();
		},
		showAllAccount(){
			return this.app().orgSelect.showAllAccount;
		},
	},
	watch: {
		selectedUUIDMap: {
			deep: true,
			handler(selectedUUIDMap) {
				this.handleChecked(selectedUUIDMap);
			}
		}
	},
	methods: {
		...mapActions('selectData', [ACTION_TOGGLE_ENTITY, ACTION_REMOVE_ENTITY, ACTION_ADD_ENTITY]),
		/**
		 * 习惯搜索条件
		 * @param value
		 * @returns {Promise<void>}
		 */
		async onChangeCondition(value) {
			let index = this.selectOptions.findIndex((el) => el.id === value);
			this.onAddSearchData({ searchType: this.selectType });
			if (index !== -1 && this.selectType !== 'unitName') {
				let enumId = this.selectOptions[index].enumId;
				let parmas = {
					panel: 'Account',
					command: 'accountMetadataData',
					arguments: { metadataId: value, enumId: enumId, showAllAccount: this.showAllAccount}
				};
				let res = await getPanelData(parmas);
				if (res.code === 0) {
					this.selectSecondOptions = res.data;
					if (this.selectSecondOptions.length > 0) {
						this.selectSecondValue = this.selectSecondOptions[0].id;
						this.onAddSearchData({ orgMetadataId: this.selectSecondValue });
						this.onSearchHandle(null);
					}
				}
			}
		},
		async doGetTreeData(data) {
			data.showAllAccount = this.showAllAccount;
			let params = {
				panel: 'Account',
				command: 'orgAccountTree',
				arguments: data
			};
			let res = await getPanelData(params);
			if (res.code !== 0) {
				return;
			}
			let resultData = res.data;
			if (resultData.length) {
				this.defaultExpandedKeys.push(resultData[0].id);
				this.handleChecked(this.selectedUUIDMap);
				this.handleGroup(resultData);
			}
			this.treeData = resultData;
		},
		onSearchHandle(value) {
			if (value === '') {
				this.searchValue = '';
				this.$refs.leftLayout.doHiddenBottom();
				this.isShowDown = true;
			} else {
				this.firstLoadSearch = true;
				this.searchValue = value === null ? '' : value;
				this.isShowDown = false;
				this.$refs.leftLayout.onHandleShow();
			}
		},
		onShowDown() {
			this.onSearchData({ ...this.searchData, keyword: this.searchValue });
		},
		onSelectSecondChange(id) {
			if (this.selectType === 'unitOrgMetadata') {
				this.onAddSearchData({ orgMetadataId: id });
			}
			this.onDoSearch();
		},
		onDoSearch() {
			this.onSearchHandle(null);
		},
		onSearchData(data) {
			this.$refs.scrollList.search(data);
		},
		onObjectHasProperty(pro) {
			let panelDefalut = this.orgSelect;
			if (Object.prototype.hasOwnProperty.call(panelDefalut, pro)) {
				this.onAddSearchData({ pro: panelDefalut[pro] });
			}
		},
		onAddSearchData(data) {
			this.searchData = { ...this.searchData, ...data };
		},
		@MaskAsync
		async onAccountCheckedNode(nodeData, nodeEl) {
			const checkNodeData = nodeData;
			const checkNodeStatus = nodeEl.checked;
			let activeCheckNode = checkNodeData.checkeds[0];
			let checkContext = {
				currentPanel: 'Account',
				notIncludeSubDept: []
			};
			// 单选处理或者没有子节点
			if (String(this.maxSize) === '1'/*单选*/
				|| (!activeCheckNode.children || activeCheckNode.children.length === 0) /*没有子节点*/
				|| activeCheckNode.id === GroupId/*集团节点*/ ) {
				if (checkNodeStatus) {
					this[ACTION_REMOVE_ENTITY]({
						entities: [activeCheckNode]
					});
					return;
				}
				if (!checkNodeStatus) {
					let rs = await CheckUtils.doCheckEntity(activeCheckNode, checkContext);
					if (!rs) {
						return;
					}
				}

				this[ACTION_TOGGLE_ENTITY]({
					entities: [activeCheckNode]
				});
				return;
			}
			if (checkNodeStatus) {
				// 取消勾选:是否取消勾选子单位
				let nodes = this.getAllChildren(activeCheckNode.children, true);
				if (nodes.length > 0) {
					let btnType = await Dialog.confirm(`"${activeCheckNode.name}"${this.$i18n('selectPeople.ifChildDept.unselected')}`);
					if (btnType === BtnType.CLOSE) {
						return;
					}
					if (btnType === BtnType.CANCEL) {
						nodes = [];
					}
				}
				nodes.push(activeCheckNode);
				this[ACTION_REMOVE_ENTITY]({
					entities: nodes
				});
				return;
			}

			let btnType = await Dialog.confirm({
				msg: `"${activeCheckNode.name}"${this.$i18n('selectPeople.ifChildDept')}`,
				okText: this.$i18n('secret.secretLevel.yes_str'),
				cancelText: this.$i18n('secret.secretLevel.no_str')
			});
			if (btnType === BtnType.CLOSE) {
				return;
			}
			// 包含子单位
			let nodes = [];
			if (btnType === BtnType.OK) {
				nodes = this.getAllChildren(activeCheckNode.children, false);
			}
			nodes.unshift(activeCheckNode);

			let entities = [];
			for (const currentNode of nodes) {
				let rs = await CheckUtils.doCheckEntity(currentNode, checkContext);
				if (!rs) {
					continue;
				}
				entities.push(currentNode);
			}
			this[ACTION_ADD_ENTITY]({
				entities
			});
		},
		getAllChildren(children, includeChecked) {
			if (!children || children.length === 0) {
				return [];
			}
			let nodes = [];
			for (let child of children) {
				let myChildren = this.getAllChildren(child.children, includeChecked);
				nodes = [...nodes, ...myChildren];
				let uuid = getSelectKey(child);
				if (includeChecked === true ) {
					if (this.selectedUUIDMap[uuid]) {
						nodes.push(child);
					}
				} else if (includeChecked === false) {
					if (!this.selectedUUIDMap[uuid]) {
						nodes.push(child);
					}
				} else {
					nodes.push(child);
				}
			}
			return nodes;
		},
		/**
		 * 回显被选中的数据
		 * @param selectedUUIDMap
		 */
		handleChecked(selectedUUIDMap) {
			let accountCheckedList = [];
			let typeIds = Object.keys(selectedUUIDMap);
			for (let item of typeIds) {
				if (item.indexOf(EntityTypes.Account) === 0) {
					accountCheckedList.push(item.split('|')[1]);
				}
			}
			this.accountCheckedList = accountCheckedList;
		},
		/**
		 * 判断集团
		 */
		handleGroup(resultData) {
			let isCanSelectGroupAccount = this.orgSelect.isCanSelectGroupAccount;

			if (isCanSelectGroupAccount) {
				return;
			}
			for (let data of resultData) {
				if (GroupId === data.id) {
					data.nocheck = true;
					break;
				}
			}
		}
	},
	created() {
		console.debug('Account created start');
		this.$nextTick(() => {
			if (this.selectOptions.length) {
				this.selectValue = this.selectOptions[0].id;
				this.onAddSearchData({ searchType: this.selectOptions[0].searchType });
			}
			this.onObjectHasProperty('onlyShowChildrenAccount');
			let { excludeElements } = this.app().orgSelect;
			if ('onlyShowChildrenAccount' in this.searchData) {
				this.doGetTreeData({
					onlyShowChildrenAccount: this.onlyShowChildrenAccount,
					excludeElements
				});
			} else {
				this.doGetTreeData({
					excludeElements
				});
			}
		});
		console.debug('Account created end');
	}
};
</script>
